package health_system.health_system.repository;

import health_system.health_system.entity.RefreshToken;
import health_system.health_system.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.Instant;
import java.util.List;
import java.util.Optional;

@Repository
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
    
    Optional<RefreshToken> findByToken(String token);
    
    @Modifying
    void deleteByUser(User user);
    
    List<RefreshToken> findAllByUser(User user);
    
    List<RefreshToken> findByUserAndDeviceId(User user, String deviceId);
    
    @Modifying
    @Query("DELETE FROM RefreshToken t WHERE t.expiryDate <= ?1")
    void deleteAllExpiredTokens(Instant now);
    
    @Modifying
    @Query("UPDATE RefreshToken t SET t.revoked = true WHERE t.user = ?1")
    void revokeAllUserTokens(User user);
    
    @Modifying
    @Query("UPDATE RefreshToken t SET t.revoked = true WHERE t.user = ?1 AND t.deviceId = ?2")
    void revokeUserTokensForDevice(User user, String deviceId);
} 